<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"sekla.cn","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="C++ STL最近开始刷Leetcode，由于很长一段时间没用到STL，发现STL基本已经只记得几个重要一点的，所以现在开始重新学习并深入STL中，这次不仅仅是会用，还会深入到STL源码中，去更好地掌握C++这门高深的语言，随便复习一下数据结构。">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解C++ STL(1)基础与迭代器">
<meta property="og:url" content="http://sekla.cn/2021/04/19/C++%20STL/index.html">
<meta property="og:site_name" content="Sekla&#39;s Blog">
<meta property="og:description" content="C++ STL最近开始刷Leetcode，由于很长一段时间没用到STL，发现STL基本已经只记得几个重要一点的，所以现在开始重新学习并深入STL中，这次不仅仅是会用，还会深入到STL源码中，去更好地掌握C++这门高深的语言，随便复习一下数据结构。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/04/22/edEhX7lT3su1FLP.png">
<meta property="article:published_time" content="2021-04-19T08:30:00.000Z">
<meta property="article:modified_time" content="2021-10-18T14:37:37.177Z">
<meta property="article:author" content="Sekla">
<meta property="article:tag" content="C++">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/04/22/edEhX7lT3su1FLP.png">

<link rel="canonical" href="http://sekla.cn/2021/04/19/C++%20STL/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>深入理解C++ STL(1)基础与迭代器 | Sekla's Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <script type="text/javascript" src="/js/my_js/clicklove.js"></script>
<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Sekla's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Keep Learning Keep Doing</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">23</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">100</span></a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://sekla.cn/2021/04/19/C++%20STL/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Sekla">
      <meta itemprop="description" content="Sekla">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sekla's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入理解C++ STL(1)基础与迭代器
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-04-19 16:30:00" itemprop="dateCreated datePublished" datetime="2021-04-19T16:30:00+08:00">2021-04-19</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-10-18 22:37:37" itemprop="dateModified" datetime="2021-10-18T22:37:37+08:00">2021-10-18</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/C/" itemprop="url" rel="index"><span itemprop="name">C++</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/C/STL/" itemprop="url" rel="index"><span itemprop="name">STL</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>4.6k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>4 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="C-STL"><a href="#C-STL" class="headerlink" title="C++ STL"></a>C++ STL</h1><p>最近开始刷Leetcode，由于很长一段时间没用到STL，发现STL基本已经只记得几个重要一点的，所以现在开始重新学习并深入STL中，这次不仅仅是会用，还会深入到STL源码中，去更好地掌握C++这门高深的语言，随便复习一下数据结构。</p>
<a id="more"></a>

<h2 id="基础理解"><a href="#基础理解" class="headerlink" title="基础理解"></a>基础理解</h2><p>STL由六大部件，也就是<strong>算法，容器，适配器，空间适配器</strong>以及<strong>仿函数</strong>组成。</p>
<p><strong>容器</strong>都是一个模板类，类中实现对数据操作，包含这样的类的实现就是容器，比如常用的vector，list，map等。</p>
<p>可以理解为容器实现了数据结构，STL同样提供了<strong>算法</strong>，其算法不依赖特定的数据结构和对象，也就是说，STL算法是由泛型实现的。</p>
<p><strong>迭代器</strong>，本质上就是指针，是对指针的泛化。</p>
<p>数据结构本身是可以相互转化相互实现，比如栈和队列可以相互实现，所以出现了<strong>适配器</strong>，STL的基本3种容器为vector，deque，list有适配器queue，stack等等，这些都是由基本容器扩展而来。适配器分三种，分别为容器适配器，迭代器适配器，函数适配器。</p>
<p><strong>仿函数</strong>，其实就是类的对象，把函数写到类中，重载了 () 运算符，让对象使用 () 时表现出调用函数的特征，仿函数是可以根据自己的需求自己定义的，比如sort()的自定义升序或降序排列。</p>
<p><strong>空间适配器</strong>，即STL中的内存池，完成对内存的申请，释放，维护。配置器有两个部分：一级空间配置器，二级空间配置器</p>
<h2 id="模板"><a href="#模板" class="headerlink" title="模板"></a>模板</h2><p>模板这里直接跳过，要注意的是类定义的静态成员是被所有实例化的对象共享的。</p>
<h2 id="迭代器"><a href="#迭代器" class="headerlink" title="迭代器"></a>迭代器</h2><p>iterator是一种对象，能够遍历容器中的元素，每个迭代器对象代表容器中确定的地址。迭代器修改了常规指针的接口，只要是行为上像迭代器的都可以叫迭代器，迭代器分为五类：输入输出迭代器，前向逆向迭代器，双向迭代器和随机迭代器。</p>
<h3 id="迭代器的使用"><a href="#迭代器的使用" class="headerlink" title="迭代器的使用"></a>迭代器的使用</h3><p>迭代器一般对容器进行一些访问操作，有些容器像vector，可以直接通过索引方式访问容器数据，但是像list，map等等基本都只能用容器实现设计内嵌的iterator类来实现专属操作。通过迭代器，可以将容器和通用算法结合在一起，只要给予算法不同的迭代器，就可以对不同容器执行相同的操作，例如find查找函数。迭代器对指针的一些基本操作如*、-&gt;、++、==、!=、=进行了重载，使其具有了遍历复杂数据结构的能力，其遍历机制取决于所遍历的数据结构，所有迭代的使用和指针的使用非常相似。通过begin，end函数获取容器的头部和尾部迭代器，end迭代器不包含在容器之内，当begin和end返回的迭代器相同时表示容器为空。</p>
<p>如一个find查找函数的实现：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> InputIterator, <span class="keyword">typename</span> T&gt;</span><br><span class="line"><span class="function">InputIterator <span class="title">find</span><span class="params">(InputIterator first, InputIterator last, <span class="keyword">const</span> T &amp;value)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (first != last &amp;&amp; *frist != value)</span><br><span class="line">        ++first;</span><br><span class="line">    <span class="keyword">return</span> first;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="迭代器的实现"><a href="#迭代器的实现" class="headerlink" title="迭代器的实现"></a>迭代器的实现</h3><p>引用系统头文件<code>#include &lt;cstddef&gt;</code>，用于定义一些类型。创建Iterator.h文件来定义五种迭代器类型：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">input_iterator_tag</span>&#123;</span>&#125;;<span class="comment">//返回输入迭代器</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">output_iterator_tag</span>&#123;</span>&#125;;<span class="comment">//返回输出迭代器</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">forward_iterator_tag</span> :</span><span class="keyword">public</span> input_iterator_tag &#123;&#125;;<span class="comment">//返回前向迭代器</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">bidirectional_iterator_tag</span> :</span><span class="keyword">public</span> forward_iterator_tag &#123;&#125;;<span class="comment">//返回双向迭代器</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">random_access_iterator_tag</span> :</span><span class="keyword">public</span> bidirectional_iterator_tag &#123;&#125;;<span class="comment">//返回随机迭代器</span></span><br></pre></td></tr></table></figure>

<h4 id="输入迭代器"><a href="#输入迭代器" class="headerlink" title="输入迭代器"></a>输入迭代器</h4><p>通过对输入迭代器解除引用，它将引用对象，而对象可能位于集合中。通常用于传递地址。</p>
<p>是只读迭代器，在每个被遍历的位置上只能读取一次。例如上面find函数参数就是输入迭代器。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>,<span class="title">class</span> <span class="title">Distance</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">struct</span> <span class="title">input_iterator</span>&#123;</span></span><br><span class="line">    <span class="keyword">typedef</span> input_iterator_tag iterator_category;<span class="comment">//返回类型</span></span><br><span class="line">    <span class="keyword">typedef</span> T                  value_type;<span class="comment">//所指对象类型</span></span><br><span class="line">    <span class="keyword">typedef</span> Distance           difference_type;<span class="comment">//迭代器间距离类型</span></span><br><span class="line">    <span class="keyword">typedef</span> T*                 pointer;<span class="comment">//操作结果类型</span></span><br><span class="line">    <span class="keyword">typedef</span> T&amp;                 reference;<span class="comment">//解引用操作结果类型</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="输出迭代器"><a href="#输出迭代器" class="headerlink" title="输出迭代器"></a>输出迭代器</h4><p>只能单步前向迭代元素，通常只返回地址。只有对容器中元素写的权限。是只写迭代器，在每个被遍历的位置上只能被写一次。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">output_iterator</span>&#123;</span></span><br><span class="line">    <span class="keyword">typedef</span> output_iterator_tag iterator_category;</span><br><span class="line">    <span class="keyword">typedef</span> <span class="keyword">void</span> value_type;</span><br><span class="line">    <span class="keyword">typedef</span> <span class="keyword">void</span> difference_type;</span><br><span class="line">    <span class="keyword">typedef</span> <span class="keyword">void</span> pointer;</span><br><span class="line">    <span class="keyword">typedef</span> <span class="keyword">void</span> reference;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h4 id="前向迭代器"><a href="#前向迭代器" class="headerlink" title="前向迭代器"></a>前向迭代器</h4><p>前向迭代器可以在一个正确的区间中进行读写操作，它拥有输入迭代器的所有特性，和输出迭代器的部分特性，以及单步向前迭代元素的能力。通常用于遍历。兼具输入和输出迭代器的能力，但是它可以对同一个位置重复进行读和写。但它不支持operator–，所以只能向前移动。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>, <span class="title">class</span> <span class="title">Distance</span>&gt; <span class="title">struct</span> <span class="title">forward_iterator</span>&#123;</span></span><br><span class="line">    <span class="keyword">typedef</span> forward_iterator_tag    iterator_category;</span><br><span class="line">    <span class="keyword">typedef</span> T                       value_type;</span><br><span class="line">    <span class="keyword">typedef</span> Distance                difference_type;</span><br><span class="line">    <span class="keyword">typedef</span> T*                      pointer;</span><br><span class="line">    <span class="keyword">typedef</span> T&amp;                      reference;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h4 id="双向迭代器"><a href="#双向迭代器" class="headerlink" title="双向迭代器"></a>双向迭代器</h4><p>该类迭代器是在前向迭代器的基础上提供了单步向后迭代元素的能力，前向迭代器的高级版。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>, <span class="title">class</span> <span class="title">Distance</span>&gt; <span class="title">struct</span> <span class="title">bidirectional_iterator</span>&#123;</span></span><br><span class="line">    <span class="keyword">typedef</span> bidirectional_iterator_tag    iterator_category;</span><br><span class="line">    <span class="keyword">typedef</span> T                        	  value_type;</span><br><span class="line">    <span class="keyword">typedef</span> Distance                      difference_type;</span><br><span class="line">    <span class="keyword">typedef</span> T*                            pointer;</span><br><span class="line">    <span class="keyword">typedef</span> T&amp;                            reference;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h4 id="随机迭代器"><a href="#随机迭代器" class="headerlink" title="随机迭代器"></a>随机迭代器</h4><p>该类迭代器能完成上面所有迭代器的工作，它自己独有的特性就是可以像指针那样进行算术计算，而不是仅仅只有单步向前或向后迭代。提供了“迭代器算术”，即在一步内可以向前或向后跳跃任意位置， 包含指针的所有操作，可进行随机访问，随意移动指定的步数。支持前面四种Iterator的所有操作，并另外支持it + n、it - n、it += n、 it -= n、it1 - it2和it[n]等操作。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span> &lt;<span class="class"><span class="keyword">class</span> <span class="title">T</span>, <span class="title">class</span> <span class="title">Distance</span>&gt; <span class="title">struct</span> <span class="title">random_access_iterator</span>&#123;</span></span><br><span class="line">    <span class="keyword">typedef</span> random_access_iterator_tag    iterator_category;</span><br><span class="line">    <span class="keyword">typedef</span> T                         value_type;</span><br><span class="line">    <span class="keyword">typedef</span> Distance                  difference_type;</span><br><span class="line">    <span class="keyword">typedef</span> T*                        pointer;</span><br><span class="line">    <span class="keyword">typedef</span> T&amp;                        reference;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p><strong>STL</strong>每种容器类型都定义了 const_iterator，只能读取容器的值，不能修改所指向容器范围内元素的值。vector、string、Deque为随机存取迭代器；List、Set、map、mutiset、multimap双向迭代器。</p>
<p><img src="https://i.loli.net/2021/04/22/edEhX7lT3su1FLP.png" alt="迭代器"></p>
<h4 id="迭代器失效"><a href="#迭代器失效" class="headerlink" title="迭代器失效"></a>迭代器失效</h4><p>容器操作如erase和insert可能导致迭代器失效。</p>
<table>
<thead>
<tr>
<th>容器</th>
<th>insert</th>
<th>erase</th>
</tr>
</thead>
<tbody><tr>
<td>list</td>
<td>不失效</td>
<td>被删除节点的迭代器失效</td>
</tr>
<tr>
<td>vector</td>
<td>vector容量(not size)不改变时，只失效之后的迭代器，否者全部失效</td>
<td>被删除节点之后的迭代器全部失效</td>
</tr>
<tr>
<td>set map</td>
<td>不失效</td>
<td>只有被删除节点的迭代器失效</td>
</tr>
</tbody></table>
<p>进行erase或insert会返回一个操作后的迭代器。</p>
<h4 id="迭代器辅助函数"><a href="#迭代器辅助函数" class="headerlink" title="迭代器辅助函数"></a>迭代器辅助函数</h4><p>迭代器实现需要两个辅助函数：advance与distance，在Algorithm.h头文件中。</p>
<p><strong>Advance</strong>：迭代器前移。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">InputIterator</span>, <span class="title">class</span> <span class="title">Distance</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">void</span> _<span class="title">advance</span>(<span class="title">InputIterator</span>&amp; <span class="title">it</span>, <span class="title">Distance</span> <span class="title">n</span>, <span class="title">input_iterator_tag</span>)&#123;</span></span><br><span class="line">    assert(n &gt;= <span class="number">0</span>);</span><br><span class="line">    <span class="keyword">while</span> (n--)&#123;<span class="comment">//当n大于0，迭代器前移n位</span></span><br><span class="line">        ++it;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">advance</span><span class="params">(InputIterator&amp; it, Distance n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">typedef</span> <span class="keyword">typename</span> iterator_traits&lt;InputIterator&gt;::iterator_category iterator_category;</span><br><span class="line">    _advance(it, n, iterator_category());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>distance</strong>：计算迭代器距离。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">InputIterator</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">typename</span> <span class="title">iterator_traits</span>&lt;InputIterator&gt;:</span>:difference_type_distance(InputIterator first, InputIterator last, input_iterator_tag)&#123;</span><br><span class="line">    <span class="keyword">typename</span> iterator_traits&lt;InputIterator&gt;::difference_type dist = <span class="number">0</span>;<span class="comment">//初始化距离</span></span><br><span class="line">    <span class="keyword">while</span> (first++ != last)&#123;<span class="comment">//当首地址不等于尾地址，距离增加</span></span><br><span class="line">      ++dist;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> dist;<span class="comment">//返回迭代器间距离</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">Iterator</span>&gt;</span></span><br><span class="line"><span class="class"><span class="title">typename</span> <span class="title">iterator_traits</span>&lt;Iterator&gt;:</span>:difference_type_distance(Iterator first, Iterator last)&#123;</span><br><span class="line">    <span class="keyword">typedef</span> <span class="keyword">typename</span> iterator_traits&lt;Iterator&gt;::iterator_category iterator_category;</span><br><span class="line">    <span class="keyword">return</span> _distance(first, last, iterator_category());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>
    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/C/" rel="tag"><i class="fa fa-tag"></i> C++</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/04/15/csapp-datalabafter/" rel="prev" title="DataLab后考证">
      <i class="fa fa-chevron-left"></i> DataLab后考证
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/05/01/csapp-practice-three/" rel="next" title="3个汇编求源码题">
      3个汇编求源码题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#C-STL"><span class="nav-number">1.</span> <span class="nav-text">C++ STL</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9F%BA%E7%A1%80%E7%90%86%E8%A7%A3"><span class="nav-number">1.1.</span> <span class="nav-text">基础理解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A8%A1%E6%9D%BF"><span class="nav-number">1.2.</span> <span class="nav-text">模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-number">1.3.</span> <span class="nav-text">迭代器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">1.3.1.</span> <span class="nav-text">迭代器的使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.3.2.</span> <span class="nav-text">迭代器的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BE%93%E5%85%A5%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-number">1.3.2.1.</span> <span class="nav-text">输入迭代器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BE%93%E5%87%BA%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-number">1.3.2.2.</span> <span class="nav-text">输出迭代器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%89%8D%E5%90%91%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-number">1.3.2.3.</span> <span class="nav-text">前向迭代器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8F%8C%E5%90%91%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-number">1.3.2.4.</span> <span class="nav-text">双向迭代器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%9A%8F%E6%9C%BA%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-number">1.3.2.5.</span> <span class="nav-text">随机迭代器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%A4%B1%E6%95%88"><span class="nav-number">1.3.2.6.</span> <span class="nav-text">迭代器失效</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%AD%E4%BB%A3%E5%99%A8%E8%BE%85%E5%8A%A9%E5%87%BD%E6%95%B0"><span class="nav-number">1.3.2.7.</span> <span class="nav-text">迭代器辅助函数</span></a></li></ol></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Sekla"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Sekla</p>
  <div class="site-description" itemprop="description">Sekla</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">100</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">23</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/ShenTiao" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;ShenTiao" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:584892986@qq.com" title="E-Mail → mailto:584892986@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=1416875904&auto=0&height=66"></iframe>
      
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Sekla</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">288k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">4:22</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  
      

<script>
  if (typeof MathJax === 'undefined') {
    window.MathJax = {
      loader: {
        source: {
          '[tex]/amsCd': '[tex]/amscd',
          '[tex]/AMScd': '[tex]/amscd'
        }
      },
      tex: {
        inlineMath: {'[+]': [['$', '$']]},
        tags: 'ams'
      },
      options: {
        renderActions: {
          findScript: [10, doc => {
            document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
              const display = !!node.type.match(/; *mode=display/);
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            });
          }, '', false],
          insertedScript: [200, () => {
            document.querySelectorAll('mjx-container').forEach(node => {
              let target = node.parentNode;
              if (target.nodeName.toLowerCase() === 'li') {
                target.parentNode.classList.add('has-jax');
              }
            });
          }, '', false]
        }
      }
    };
    (function () {
      var script = document.createElement('script');
      script.src = '//cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
      script.defer = true;
      document.head.appendChild(script);
    })();
  } else {
    MathJax.startup.document.state(0);
    MathJax.texReset();
    MathJax.typeset();
  }
</script>

    

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"left","width":250,"height":500},"mobile":{"show":false},"react":{"opacity":0.9},"log":false});</script></body>
</html>

<script type="text/javascript" src="/js/src/love.js"></script>
